import { Message } from '@arco-design/web-react';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { delay } from '../utils/utils';
interface Props {
  className?: string;
  children: any;
  text: string;
  onSuccess?: () => void;
}
export default function CopyToClipboard({ className, children, text, onSuccess }: Props) {
  function handleCopy(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {
    e.stopPropagation();
    e.preventDefault();
    copyToClipboard(text, onSuccess);
  }
  return (
    <div className={`copy-to-clipboard ${className}`} onClick={handleCopy}>
      {children}
    </div>
  );
}

export async function copyToClipboard(text: string, onSuccess?: () => void) {
  if (!text) {
    return Message.warning('内容为空,不可复制');
  }
  let copyOk = false;
  try {
    // 使用现代的剪贴板 API
    await navigator.clipboard.writeText(text);
    if (onSuccess) {
      onSuccess();
    } else {
      Message.success('复制成功');
    }
    copyOk = true;
  } catch (error) {
    // Message.error('复制失败，请重试');
  }
  if (!copyOk) {
    let div = document.createElement('div');
    document.body.appendChild(div);
    const root = ReactDOM.createRoot(div);
    root.render(
      <div className={`copy-to-clipboard`}>
        <textarea id="copyToClipboard" defaultValue={text} className="text-area"></textarea>
      </div>
    );
    await delay(200);
    let ta: HTMLTextAreaElement | null = document.getElementById('copyToClipboard') as HTMLTextAreaElement | null;
    if (ta) {
      ta.select();
      let res = document.execCommand('copy');
      if (res) {
        if (onSuccess) {
          onSuccess();
        } else {
          Message.success('复制成功');
        }
      }
    }
    await delay(500);
    root.unmount();
    document.body.removeChild(div);
  }
}
